import { WereWolfNextTool } from "@/werewolf/components/nextTool";
import { WereWolfDiscussPhase } from "@/werewolf/phases/discuss";
import { WereWolfPhaseView } from "@/werewolf/phaseView";
import { WereWolfPlayer } from "@/werewolf/player";
import { WereWolfNoColor } from "@/werewolf/static";
import { ScriptRunner } from "@sapi-game/Runner/scriptRunner";

export class DisussCampView extends WereWolfPhaseView<WereWolfDiscussPhase> {
    agreeCnt = 0;

    override async runPhaseView(r: ScriptRunner): Promise<void> {
        this.players.title("§e讨论时间", "§1半数人决定结束讨论后进入投票阶段");
        this.players.playSound("note.flute");
        this.waitForAgree();
        //清空同意状态
        this.context.players.getAll().forEach((p) => (p.agreed = false));
    }

    waitForAgree() {
        this.state.addComponent(WereWolfNextTool, {
            onUse: (p) => this.agree(p),
            shouldClearAll: false,
            getPlayers: () =>
                this.context.players.filter(
                    (p) => p.player != undefined && !p.dead
                ),
        });
        this.state.getComponent(WereWolfNextTool).giveNextItemToAll();
    }

    agree(player: WereWolfPlayer) {
        if (player.agreed) return player.sendMessage("§c你已经同意结束讨论");
        player.agreed = true;
        this.agreeCnt++;
        this.players.sendMessage(
            WereWolfNoColor[player.no - 1] +
                `[${player.no}号]${
                    player.name
                }§a投票选择结束讨论阶段\n§e§l当前票数:${
                    this.agreeCnt
                }/${Math.ceil(this.context.players.validSize / 2)}`
        );
        if (this.agreeCnt >= Math.ceil(this.context.players.validSize / 2)) {
            this.state.getComponent(WereWolfNextTool).clearAll();
            this.state.next();
        }
    }
}
